from fastapi import APIRouter, status, Query, Depends
from typing import Optional
from app.modules.system.models import SystemConfigModel
from app.modules.system.schemas import (
    SystemConfigCreate, SystemConfigUpdate, SystemConfigResponse, SystemConfigListResponse,
    SystemConfigBatchUpdate, SystemConfigImport, SystemConfigExport
)
from app.modules.system.services import SystemConfigService
from app.core.responses import success_response
from app.core.dependencies import get_current_user
from app.modules.users.models import UserModel

router = APIRouter(
    prefix="/api/system",
    tags=["系统管理"],
    dependencies=[Depends(get_current_user)]
)

# 公开接口，不需要认证
public_router = APIRouter(
    prefix="/api/system",
    tags=["系统管理"]
)


@router.post("/configs", summary="创建系统配置", response_model=SystemConfigResponse)
async def create_config(
    config_in: SystemConfigCreate,
    current_user: UserModel = Depends(get_current_user)
):
    """创建新的系统配置"""
    result = await SystemConfigService.create_config(config_in)
    return success_response(
        data=SystemConfigResponse.from_orm(result),
        message="配置创建成功",
        code=status.HTTP_201_CREATED
    )


@router.get("/configs", summary="获取系统配置列表", response_model=SystemConfigListResponse)
async def get_config_list(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    key: Optional[str] = Query(None, description="配置键（模糊搜索）"),
    type: Optional[str] = Query(None, description="配置类型"),
    is_system: Optional[bool] = Query(None, description="是否系统配置"),
    is_public: Optional[bool] = Query(None, description="是否公开配置")
):
    """获取系统配置分页列表"""
    total, items = await SystemConfigService.get_config_list(
        skip=(page - 1) * size,
        limit=size,
        key=key,
        type=type,
        is_system=is_system,
        is_public=is_public
    )
    
    return success_response(data={
        "total": total,
        "items": [SystemConfigResponse.from_orm(item) for item in items]
    })


@router.get("/configs/{config_id}", summary="获取系统配置详情", response_model=SystemConfigResponse)
async def get_config_detail(config_id: int):
    """根据ID获取系统配置详情"""
    result = await SystemConfigService.get_config_by_id(config_id)
    return success_response(data=SystemConfigResponse.from_orm(result))


@router.get("/configs/key/{key}", summary="根据键获取配置值")
async def get_config_by_key(key: str):
    """根据配置键获取配置值"""
    config = await SystemConfigService.get_config_by_key(key)
    if not config:
        return success_response(data=None, message="配置不存在")
    
    # 根据类型转换值
    from app.modules.system.services import SystemConfigService
    value = SystemConfigService._convert_value(config.value, config.type)
    
    return success_response(data={
        "key": config.key,
        "value": value,
        "type": config.type,
        "description": config.description
    })


@router.patch("/configs/{config_id}", summary="更新系统配置", response_model=SystemConfigResponse)
async def update_config(
    config_id: int,
    config_in: SystemConfigUpdate
):
    """更新系统配置"""
    result = await SystemConfigService.update_config(config_id, config_in)
    return success_response(
        data=SystemConfigResponse.from_orm(result),
        message="配置更新成功"
    )


@router.delete("/configs/{config_id}", summary="删除系统配置")
async def delete_config(config_id: int):
    """删除系统配置"""
    await SystemConfigService.delete_config(config_id)
    return success_response(message="配置删除成功")


@router.post("/configs/batch-update", summary="批量更新配置")
async def batch_update_configs(config_in: SystemConfigBatchUpdate):
    """批量更新系统配置"""
    result = await SystemConfigService.batch_update_configs(config_in.configs)
    return success_response(
        data=[SystemConfigResponse.from_orm(item) for item in result],
        message=f"批量更新成功，共更新 {len(result)} 个配置"
    )


@router.get("/configs/public", summary="获取公开配置")
async def get_public_configs():
    """获取所有公开配置"""
    configs = await SystemConfigService.get_public_configs()
    return success_response(data=[
        {
            "key": config.key,
            "value": SystemConfigService._convert_value(config.value, config.type),
            "type": config.type,
            "description": config.description
        }
        for config in configs
    ])


@router.get("/configs/system", summary="获取系统配置")
async def get_system_configs():
    """获取所有系统配置"""
    configs = await SystemConfigService.get_system_configs()
    return success_response(data=[
        SystemConfigResponse.from_orm(config) for config in configs
    ])


@router.post("/configs/export", summary="导出系统配置")
async def export_configs(config_in: SystemConfigExport):
    """导出系统配置"""
    result = await SystemConfigService.export_configs(
        keys=config_in.keys,
        include_system=config_in.include_system,
        include_private=config_in.include_private
    )
    return success_response(
        data=result,
        message=f"导出成功，共 {len(result)} 个配置"
    )


@router.post("/configs/import", summary="导入系统配置")
async def import_configs(config_in: SystemConfigImport):
    """导入系统配置"""
    configs_data = [config.dict() for config in config_in.configs]
    result = await SystemConfigService.import_configs(configs_data)
    return success_response(
        data=[SystemConfigResponse.from_orm(item) for item in result],
        message=f"导入成功，共导入 {len(result)} 个配置"
    )


@router.get("/configs/types", summary="获取配置类型列表")
async def get_config_types():
    """获取支持的配置类型列表"""
    types = [
        {"value": "string", "label": "字符串"},
        {"value": "int", "label": "整数"},
        {"value": "float", "label": "浮点数"},
        {"value": "bool", "label": "布尔值"},
        {"value": "json", "label": "JSON"}
    ]
    return success_response(data=types)


# 公开接口 - 获取公开配置（不需要认证）
@public_router.get("/configs/public", summary="获取公开配置（无需认证）")
async def get_public_configs_no_auth():
    """获取所有公开配置（无需认证）"""
    configs = await SystemConfigService.get_public_configs()
    return success_response(data=[
        {
            "key": config.key,
            "value": SystemConfigService._convert_value(config.value, config.type),
            "type": config.type,
            "description": config.description
        }
        for config in configs
    ])


@public_router.get("/configs/key/{key}", summary="根据键获取配置值（无需认证）")
async def get_config_by_key_no_auth(key: str):
    """根据配置键获取配置值（无需认证）"""
    config = await SystemConfigService.get_config_by_key(key)
    if not config:
        return success_response(data=None, message="配置不存在")
    
    # 只有公开配置才能通过公开接口访问
    if not config.is_public:
        return success_response(data=None, message="配置不存在")
    
    # 根据类型转换值
    value = SystemConfigService._convert_value(config.value, config.type)
    
    return success_response(data={
        "key": config.key,
        "value": value,
        "type": config.type,
        "description": config.description
    }) 